//
// Created by hjie on 23-6-11.
//

#include "media_process.h"


MediaProcess::MediaProcess(const std::string &file_name)
{
    m_file_name = file_name;
    m_thread_msg_queue = NULL;
}

MediaProcess::~MediaProcess()
{
    if (m_thd.joinable())
    {
        m_thd.join();
    }
}

void MediaProcess::StartReadThread()
{
    m_thd = std::thread([this](){

        ReadAvPacket();
    });
    if (m_thread_msg_queue != NULL)
    {
        av_thread_message_queue_free(&m_thread_msg_queue);
    }
}

void MediaProcess::ReadAvPacket()
{
    AVFormatContext * format_ctx = NULL;

    if (avformat_open_input(&format_ctx, m_file_name.c_str(), NULL, NULL) < 0)
    {
        printf("avformat_open_input failed\n");
        return;
    }
    printf("[%s] open file ok\n", __func__);
    avformat_find_stream_info(format_ctx, NULL);
    av_dump_format(format_ctx, 0, m_file_name.c_str(), 0);

    av_thread_message_queue_alloc(&m_thread_msg_queue, 40000, sizeof(AVPacket*));

    AVPacket * packet = av_packet_alloc();
    while (av_read_frame(format_ctx, packet) >= 0)
    {
        AVPacket * pkt = av_packet_alloc();
        av_packet_move_ref(pkt, packet);
        if (av_thread_message_queue_send(m_thread_msg_queue, &pkt, 0) < 0)
        {
            break;
        }
    }
    printf("stop read packet data\n");
    av_thread_message_queue_set_err_recv(m_thread_msg_queue, AVERROR_EOF);
    av_packet_free(&packet);
    avformat_close_input(&format_ctx);
    avformat_free_context(format_ctx);
}

int MediaProcess::GetAvPacket(AVPacket ** packet)
{
    if (m_thread_msg_queue == NULL)
    {
        return -1;
    }
    AVPacket * pkt = NULL;
    return av_thread_message_queue_recv(m_thread_msg_queue, packet, AV_THREAD_MESSAGE_NONBLOCK);
}

